import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Form, Button, Drawer, Icon, Popconfirm, Divider, notification, message } from 'antd';

import { isNumber } from '../../utils/tools';
import StandardTableCustom from '../../customComponents/StandardTableCustom';
import styles from './CorrelationDrawer.less';

@connect(({ orderProcessing, global, loading }) => ({
  orderProcessing,
  global,
  loading: loading.models.orderProcessing,
}))
@Form.create()
class DrawerDapperBySelfBuild extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      dataLoading: false,
      processing: false,
      visible: false,
      recordKey: null,
      mainRecord: null,
      customData: [],
    };
  }

  componentDidMount() {
    const { visible, recordKey, record } = this.props;
    this.setState({ visible, recordKey, mainRecord: record });

    if (isNumber(recordKey)) {
      this.loadData({
        lineId: recordKey,
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    const { recordKey: recordKeyPre, dataLoading } = this.state;
    const { visible, recordKey: recordKeyNext, record } = nextProps;
    this.setState({ visible, recordKey: recordKeyNext, mainRecord: record });

    if (recordKeyPre !== recordKeyNext && isNumber(recordKeyNext) && !dataLoading) {
      this.setState({ dataLoading: true });
      setTimeout(() => {
        this.loadData({
          lineId: recordKeyNext,
        });
      }, 700);
    }
  }

  loadData = params => {
    const { dispatch } = this.props;
    const submitData = params;

    this.setState({ dataLoading: true });

    dispatch({
      type: 'orderProcessing/listCommunityOrder',
      payload: submitData,
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      this.setState({ customData: data }, () => {
        this.setState({ dataLoading: false });
      });
    });
  };

  handleSelectRows = rows => {
    // const list = [];
    // rows.forEach(o => {
    //   list.push(`${o.name}|${o.dataEntityType}`);
    // });
    // const v = list.join();
    // this.setState({
    //   tableList: v,
    // });

    this.setState({
      selectedDataTableDataRows: rows,
    });
  };

  onClose = () => {
    const { afterClose } = this.props;
    afterClose();
  };

  setCommunityTransit = (e, record) => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setCommunityTransit',
      payload: {
        lineId: record.lineId,
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomLeft',
            message: '出库操作执行结果',
            description: `社区’${record.communityName}‘已经设置出库`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomLeft',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setCommunityTransitCannel = (e, record) => {
    message.warn(`社区’${record.communityName}‘取消出库操作`);
  };

  setCommunityPrint = (e, record) => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setCommunityPrint',
      payload: {
        lineId: record.lineId,
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomLeft',
            message: '出库操作执行结果',
            description: `社区’${record.communityName}‘打印三联总单已经传送打印机`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomLeft',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setCommunityPrintCannel = (e, record) => {
    message.warn(`社区’${record.communityName}‘取消打印三联总单`);
  };

  setSinglePrint = (e, record) => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setSinglePrint',
      payload: {
        lineId: record.lineId,
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomLeft',
            message: '出库操作执行结果',
            description: `社区’${record.communityName}‘打印A4分单已经传送打印机`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomLeft',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setSinglePrintCannel = (e, record) => {
    message.warn(`社区’${record.communityName}‘取消A4分单打印`);
  };

  setCommunityDispatch = (e, record) => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setCommunityDispatch',
      payload: {
        lineId: record.lineId,
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomLeft',
            message: '出库操作执行结果',
            description: `社区’${record.communityName}‘已设置配送`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomLeft',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setCommunityDispatchCannel = (e, record) => {
    message.warn(`社区’${record.communityName}‘取消配送操作`);
  };

  setSingleLineTransit = (e, record) => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setSingleLineTransit',
      payload: {
        lineId: record.lineId,
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomLeft',
            message: '出库操作执行结果',
            description: `’${record.lineName}‘已经设置出库`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomLeft',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setSingleLineTransitCannel = (e, record) => {
    message.warn(`线路’${record.lineName}‘取消出库操作`);
  };

  setSingleLinePrint = (e, record) => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'orderProcessing/setSingleLinePrint',
      payload: {
        lineId: record.lineId,
      },
    }).then(() => {
      const {
        orderProcessing: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomLeft',
            message: '打印操作执行结果',
            description: `’${record.lineName}‘已经传输给打印机。`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomLeft',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setSingleLinePrintCannel = (e, record) => {
    message.warn(`线路’${record.lineName}‘取消打印操作。`);
  };

  goToEdit = record => {
    const { dispatch } = this.props;
    const { intorderProcessingid } = record;
    const location = {
      pathname: `/orderProcessing/edit/load/${intorderProcessingid}/basicInfo`,
    };
    dispatch(routerRedux.push(location));
  };

  render() {
    const { title: titleDrawer, width: widthDrawer } = this.props;
    const { selectDatabaseName } = this.props;
    const {
      visible,
      dataLoading,
      processing,
      customData,
      selectedDataTableDataRows,
      mainRecord,
    } = this.state;

    const columns = [
      {
        title: '社区信息',
        dataIndex: 'lineId',
        align: 'left',
        render: (val, record) => (
          <Fragment>
            <span
              className={styles.communityName}
              onClick={() => {
                this.showCorrelationDrawer(record);
              }}
            >
              {record.communityName}
            </span>
            <span className={styles.communitySaler}>
              {`${record.communitySalerName}*${record.lineName}`}
            </span>
          </Fragment>
        ),
      },
      {
        title: '操作',
        width: 556,
        align: 'right',
        // fixed: 'right',
        render: (text, record) => (
          <Fragment>
            <a className={styles.actionButton}>
              <Icon type="swap" className={styles.editButton} />
              切换线路
            </a>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="将出库社区订单，确定吗？"
              onConfirm={e => this.setCommunityTransit(e, record)}
              onCancel={e => this.setCommunityTransitCannel(e, record)}
              okText="确定"
              cancelText="取消"
            >
              <a className={styles.actionButton}>
                <Icon type="export" className={styles.editButton} />
                社区出库
              </a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="将打印三联单社区总单，确定吗？"
              onConfirm={e => this.setCommunityPrint(e, record)}
              onCancel={e => this.setCommunityPrintCannel(e, record)}
              okText="确定"
              cancelText="取消"
            >
              <a className={styles.actionButton}>
                <Icon type="printer" className={styles.editButton} />
                打三联单社区总单
              </a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="将打印A4分单，确定吗？"
              onConfirm={e => this.setSinglePrint(e, record)}
              onCancel={e => this.setSinglePrintCannel(e, record)}
              okText="确定"
              cancelText="取消"
            >
              <a className={styles.actionButton}>
                <Icon type="printer" className={styles.editButton} />
                打A4分单
              </a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="将设置配送订单，确定吗？"
              onConfirm={e => this.setCommunityDispatch(e, record)}
              onCancel={e => this.setCommunityDispatchCannel(e, record)}
              okText="确定"
              cancelText="取消"
            >
              <a className={styles.actionButton}>
                <Icon type="retweet" className={styles.editButton} />
                配送
              </a>
            </Popconfirm>
            <Divider type="vertical" />
            <a className={styles.actionButton}>
              <Icon type="book" className={styles.editButton} />
              查看
            </a>
          </Fragment>
        ),
      },
    ];

    return (
      <Drawer
        title={
          <span>
            <Icon type="read" className={styles.titleIcon} />
            {titleDrawer}
          </span>
        }
        className={styles.containorBox}
        width={widthDrawer}
        placement="right"
        visible={visible}
        selectDatabaseName={selectDatabaseName}
        maskClosable={false}
        onClose={this.onClose}
        style={{
          height: 'calc(100% - 55px)',
        }}
      >
        <div>
          <StandardTableCustom
            loading={dataLoading || processing}
            data={customData}
            columns={columns}
            pagination={false}
            expandedRowRender={record => (
              <div>
                <p>
                  <span className={styles.bold}>订单总计：</span>
                  <span>{`共${record.productCount}件商品，共计${record.totalAmount}元`}</span>
                </p>
              </div>
            )}
            // showSelect
            selectedRows={selectedDataTableDataRows}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
          <div className={styles.bottomBar}>
            <Popconfirm
              placement="topRight"
              title="将打印三联总单，确定吗？"
              onConfirm={e => this.setSingleLinePrint(e, mainRecord)}
              onCancel={e => this.setSingleLinePrintCannel(e, mainRecord)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="primary"
                icon="printer"
                loading={processing}
                disabled={dataLoading || processing}
                onClick={this.openFolder}
              >
                打印线路三联总单
              </Button>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="全部开始出库，确定吗？"
              onConfirm={e => this.setSingleLineTransit(e, mainRecord)}
              onCancel={e => this.setSingleLineTransitCannel(e, mainRecord)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="primary"
                htmlType="submit"
                onClick={this.handleOk}
                icon="export"
                loading={processing}
                disabled={dataLoading || processing}
              >
                线路开始出库
              </Button>
            </Popconfirm>
            <Divider type="vertical" />
            <Button
              style={{
                marginRight: 8,
              }}
              icon="close"
              onClick={this.onClose}
            >
              关闭面版
            </Button>
          </div>
        </div>
      </Drawer>
    );
  }
}

export default DrawerDapperBySelfBuild;
